package com.icongyou.enterprise.talent_analysis.service.impl;

import com.icongyou.enterprise.data_aggregation.entity.GradeEntity;
import com.icongyou.enterprise.data_aggregation.entity.SubmissionEntity;
import com.icongyou.enterprise.data_aggregation.entity.UserEntity;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_analysis.entity.*;
import com.icongyou.enterprise.talent_analysis.service.AIInsightService;
import com.icongyou.enterprise.talent_analysis.service.AIPortraitEvaluationService;
import com.icongyou.enterprise.talent_analysis.service.HrTemplatePreferenceService;
import com.icongyou.enterprise.talent_analysis.service.PortraitService;
import com.icongyou.enterprise.talent_analysis.service.WordCloudService;
import com.icongyou.enterprise.talent_analysis.service.support.AIClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * AI辅助洞察服务实现
 * 基于学生的能力画像和任务表现数据生成AI洞察
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AIInsightServiceImpl implements AIInsightService {
    
    private final DataAggregationService dataAggregationService;
    private final PortraitService portraitService;
    private final AIPortraitEvaluationService aiPortraitService;
    private final HrTemplatePreferenceService preferenceService;
    private final WordCloudService wordCloudService;
    private final AIClient aiClient;
    private final StudentFeatureExtractor featureExtractor;
    
    @Override
    public StudentInsight generateStudentInsight(String studentId, String hrUserId) {
        
        StudentInsight insight = new StudentInsight();
        insight.setStudentId(studentId);
        insight.setGeneratedTime(LocalDateTime.now());
        insight.setAiModelVersion("GPT-4");
        
        // 1. 获取学生基础信息
        UserEntity student = dataAggregationService.getStudentById(studentId);
        if (student == null) {
            return insight;
        }
        insight.setStudentName(student.getRealName());
        insight.setMajor(student.getMajor());
        
        // 2. 获取能力画像数据（雷达图 - 智能适配默认/自定义模板）
        PortraitResponse portrait = getPortraitWithPreference(studentId, hrUserId);
        
        // 3. 分析任务类别表现
        TaskCategoryAnalysis taskAnalysis = analyzeTaskCategoryPerformance(studentId);
        insight.setTaskCategoryAnalysis(taskAnalysis);
        
        // 4. 提取维度亮点
        insight.setDimensionHighlights(extractDimensionHighlights(portrait));
        
        // 5. 调用AI生成岗位推荐
        insight.setJobRecommendations(generateJobRecommendationsWithAI(studentId, portrait, taskAnalysis));
        
        // 6. 调用AI分析优缺点
        Map<String, List<String>> strengthsWeaknesses = analyzeStrengthsAndWeaknesses(studentId, hrUserId);
        insight.setStrengths(strengthsWeaknesses.get("strengths"));
        insight.setWeaknesses(strengthsWeaknesses.get("weaknesses"));
        
        // 7. 生成综合评价
        insight.setOverallEvaluation(generateOverallEvaluation(studentId, portrait, taskAnalysis));
        
        // 8. 生成职业发展建议
        insight.setCareerAdvice(generateCareerAdvice(studentId, hrUserId));
        
        return insight;
    }
    
    @Override
    public TaskCategoryAnalysis analyzeTaskCategoryPerformance(String studentId) {
        
        TaskCategoryAnalysis analysis = new TaskCategoryAnalysis();
        
        // 获取学生的所有提交记录
        List<SubmissionEntity> submissions = getAllSubmissions(studentId);
        if (submissions.isEmpty()) {
            analysis.setAiSummary("暂无任务提交数据");
            return analysis;
        }
        
        // 按任务类型分类统计
        Map<String, List<SubmissionEntity>> byType = submissions.stream()
            .collect(Collectors.groupingBy(s -> s.getTeamId() != null ? "团队任务" : "个人任务"));
        
        for (Map.Entry<String, List<SubmissionEntity>> entry : byType.entrySet()) {
            String type = entry.getKey();
            List<SubmissionEntity> subs = entry.getValue();
            
            TaskCategoryAnalysis.CategoryPerformance perf = calculateCategoryPerformance(type, subs);
            analysis.getPerformanceByType().put(type, perf);
        }
        
        // 识别高分和低分任务
        analysis.setHighScoreTasks(identifyHighScoreTasks(submissions));
        analysis.setLowScoreTasks(identifyLowScoreTasks(submissions));
        
        // 分析趋势
        analysis.setPerformanceTrend(analyzePerformanceTrend(submissions));
        
        // AI生成总结
        analysis.setAiSummary(generateTaskAnalysisSummary(analysis));
        
        return analysis;
    }
    
    @Override
    public List<JobRecommendation> recommendJobs(String studentId, int topN, String hrUserId) {
        
        PortraitResponse portrait = getPortraitWithPreference(studentId, hrUserId);
        TaskCategoryAnalysis taskAnalysis = analyzeTaskCategoryPerformance(studentId);
        
        List<JobRecommendation> recommendations = generateJobRecommendationsWithAI(studentId, portrait, taskAnalysis);
        
        return recommendations.stream()
            .limit(Math.min(topN, 5))
            .collect(Collectors.toList());
    }
    
    @Override
    public Map<String, List<String>> analyzeStrengthsAndWeaknesses(String studentId, String hrUserId) {
        
        Map<String, List<String>> result = new HashMap<>();
        result.put("strengths", new ArrayList<>());
        result.put("weaknesses", new ArrayList<>());
        
        // 获取能力画像（智能适配模板偏好）
        PortraitResponse portrait = getPortraitWithPreference(studentId, hrUserId);
        
        // 获取任务表现
        TaskCategoryAnalysis taskAnalysis = analyzeTaskCategoryPerformance(studentId);
        
        // 获取教师评价关键词
        Map<String, Integer> keywords = wordCloudService.getWordCloud(studentId);
        
        // 构建AI提示词
        String prompt = buildStrengthWeaknessPrompt(studentId, portrait, taskAnalysis, keywords);
        
        // 调用AI分析
        try {
            String aiResponse = aiClient.chat(prompt);
            parseStrengthWeaknessResponse(aiResponse, result);
        } catch (Exception e) {
            // 降级：使用规则生成
            generateRuleBasedStrengthWeakness(portrait, taskAnalysis, result);
        }
        
        return result;
    }
    
    @Override
    public String generateCareerAdvice(String studentId, String hrUserId) {
        
        PortraitResponse portrait = getPortraitWithPreference(studentId, hrUserId);
        TaskCategoryAnalysis taskAnalysis = analyzeTaskCategoryPerformance(studentId);
        UserEntity student = dataAggregationService.getStudentById(studentId);
        
        String prompt = buildCareerAdvicePrompt(student, portrait, taskAnalysis);
        
        try {
            return aiClient.chat(prompt);
        } catch (Exception e) {
            return "根据您的能力表现，建议继续加强弱项能力，巩固优势领域，积极参与项目实践。";
        }
    }
    
    // ==================== 私有辅助方法 ====================
    
    /**
     * 根据HR偏好智能获取能力画像
     * 如果HR设置了自定义模板,则使用自定义维度;否则使用默认6维度
     */
    private PortraitResponse getPortraitWithPreference(String studentId, String hrUserId) {
        // 检查HR用户的模板偏好
        String templateId = null;
        if (hrUserId != null) {
            try {
                templateId = preferenceService.getCurrentTemplateId(hrUserId);
            } catch (Exception e) {
            }
        }
        
        // 根据模板偏好获取画像
        PortraitResponse response;
        if (templateId == null) {
            response = portraitService.computeDefaultPortrait(studentId);
        } else {
            response = aiPortraitService.computeCustomPortrait(studentId, templateId);
            
            // 检查是否因维度不明确而降级
            if (response.isDimensionsUnclear() && response.isFallbackToDefault()) {
            }
        }
        
        return response;
    }
    
    /**
     * 获取学生所有提交记录
     */
    private List<SubmissionEntity> getAllSubmissions(String studentId) {
        List<SubmissionEntity> allSubmissions = new ArrayList<>();
        
        dataAggregationService.getStudentCourse(studentId).forEach(course -> {
            dataAggregationService.getStudentSubmissionsByCourse(studentId, course.getCourseId())
                .forEach(allSubmissions::add);
        });
        
        return allSubmissions;
    }
    
    /**
     * 计算某类别任务的表现统计
     */
    private TaskCategoryAnalysis.CategoryPerformance calculateCategoryPerformance(
        String category, 
        List<SubmissionEntity> submissions
    ) {
        TaskCategoryAnalysis.CategoryPerformance perf = new TaskCategoryAnalysis.CategoryPerformance();
        perf.setCategory(category);
        perf.setTaskCount(submissions.size());
        
        // 获取所有成绩
        List<BigDecimal> scores = new ArrayList<>();
        int onTimeCount = 0;
        int excellentCount = 0;
        
        for (SubmissionEntity sub : submissions) {
            List<GradeEntity> grades = dataAggregationService.getStudentGrade(sub.getSubmissionId());
            if (!grades.isEmpty()) {
                BigDecimal score = grades.get(0).getFinalScore();
                if (score != null) {
                    scores.add(score);
                    if (score.compareTo(BigDecimal.valueOf(90)) >= 0) {
                        excellentCount++;
                    }
                }
            }
            
            if (sub.getIsLate() != null && sub.getIsLate() == 0) {
                onTimeCount++;
            }
        }
        
        if (!scores.isEmpty()) {
            perf.setAvgScore(scores.stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add)
                .divide(BigDecimal.valueOf(scores.size()), 2, RoundingMode.HALF_UP));
            perf.setMaxScore(scores.stream().max(BigDecimal::compareTo).orElse(BigDecimal.ZERO));
            perf.setExcellenceRate(excellentCount * 100.0 / scores.size());
        }
        
        perf.setCompletionRate(100.0);
        perf.setOnTimeRate(onTimeCount * 100.0 / submissions.size());
        
        return perf;
    }
    
    /**
     * 识别高分任务
     */
    private List<TaskCategoryAnalysis.TaskDetail> identifyHighScoreTasks(List<SubmissionEntity> submissions) {
        return submissions.stream()
            .map(this::convertToTaskDetail)
            .filter(Objects::nonNull)
            .filter(task -> task.getScoreRate() != null && task.getScoreRate() >= 90.0)
            .sorted(Comparator.comparing(TaskCategoryAnalysis.TaskDetail::getScoreRate).reversed())
            .limit(5)
            .collect(Collectors.toList());
    }
    
    /**
     * 识别低分任务
     */
    private List<TaskCategoryAnalysis.TaskDetail> identifyLowScoreTasks(List<SubmissionEntity> submissions) {
        return submissions.stream()
            .map(this::convertToTaskDetail)
            .filter(Objects::nonNull)
            .filter(task -> task.getScoreRate() != null && task.getScoreRate() < 60.0)
            .sorted(Comparator.comparing(TaskCategoryAnalysis.TaskDetail::getScoreRate))
            .limit(3)
            .collect(Collectors.toList());
    }
    
    /**
     * 转换为任务详情
     */
    private TaskCategoryAnalysis.TaskDetail convertToTaskDetail(SubmissionEntity submission) {
        List<GradeEntity> grades = dataAggregationService.getStudentGrade(submission.getSubmissionId());
        if (grades.isEmpty()) {
            return null;
        }
        
        GradeEntity grade = grades.get(0);
        TaskCategoryAnalysis.TaskDetail detail = new TaskCategoryAnalysis.TaskDetail();
        detail.setTaskId(submission.getAssignmentId());
        detail.setTaskName("任务-" + submission.getAssignmentId().substring(0, 8));
        detail.setTaskType(submission.getTeamId() != null ? "团队" : "个人");
        detail.setScore(grade.getFinalScore());
        // 这里简化处理，实际应该从assignments表获取fullScore
        detail.setFullScore(BigDecimal.valueOf(100));
        
        if (grade.getFinalScore() != null) {
            detail.setScoreRate(grade.getFinalScore().doubleValue());
        }
        
        detail.setTeacherCommentSummary(
            grade.getTextComment() != null && !grade.getTextComment().isEmpty() 
                ? grade.getTextComment().substring(0, Math.min(50, grade.getTextComment().length())) + "..."
                : "无评价"
        );
        
        return detail;
    }
    
    /**
     * 分析表现趋势
     */
    private String analyzePerformanceTrend(List<SubmissionEntity> submissions) {
        if (submissions.size() < 3) {
            return "数据不足，无法分析趋势";
        }
        
        // 按时间排序，比较前半部分和后半部分的平均分
        List<SubmissionEntity> sorted = submissions.stream()
            .sorted(Comparator.comparing(SubmissionEntity::getSubmissionTime))
            .collect(Collectors.toList());
        
        int mid = sorted.size() / 2;
        List<SubmissionEntity> firstHalf = sorted.subList(0, mid);
        List<SubmissionEntity> secondHalf = sorted.subList(mid, sorted.size());
        
        double firstAvg = calculateAverageScore(firstHalf);
        double secondAvg = calculateAverageScore(secondHalf);
        
        double diff = secondAvg - firstAvg;
        
        if (diff > 5) {
            return "进步明显（提升" + String.format("%.1f", diff) + "分）";
        } else if (diff < -5) {
            return "有所下滑（下降" + String.format("%.1f", Math.abs(diff)) + "分）";
        } else {
            return "保持稳定";
        }
    }
    
    /**
     * 计算平均分
     */
    private double calculateAverageScore(List<SubmissionEntity> submissions) {
        List<Double> scores = submissions.stream()
            .flatMap(s -> dataAggregationService.getStudentGrade(s.getSubmissionId()).stream())
            .map(GradeEntity::getFinalScore)
            .filter(Objects::nonNull)
            .map(BigDecimal::doubleValue)
            .collect(Collectors.toList());
        
        return scores.isEmpty() ? 0.0 : scores.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
    }
    
    /**
     * 生成任务分析总结
     */
    private String generateTaskAnalysisSummary(TaskCategoryAnalysis analysis) {
        StringBuilder summary = new StringBuilder();
        
        for (TaskCategoryAnalysis.CategoryPerformance perf : analysis.getPerformanceByType().values()) {
            summary.append(String.format("%s：完成%d个任务，平均分%.1f，优秀率%.1f%%。",
                perf.getCategory(),
                perf.getTaskCount(),
                perf.getAvgScore() != null ? perf.getAvgScore().doubleValue() : 0.0,
                perf.getExcellenceRate() != null ? perf.getExcellenceRate() : 0.0
            ));
        }
        
        summary.append("表现趋势：").append(analysis.getPerformanceTrend()).append("。");
        
        return summary.toString();
    }
    
    /**
     * 提取维度亮点
     */
    private List<StudentInsight.DimensionHighlight> extractDimensionHighlights(PortraitResponse portrait) {
        List<StudentInsight.DimensionHighlight> highlights = new ArrayList<>();
        
        for (int i = 0; i < portrait.getLabels().size() && i < portrait.getScores().size(); i++) {
            String dimension = portrait.getLabels().get(i);
            Double score = portrait.getScores().get(i);
            
            if (score >= 4.0) { // 高分维度
                StudentInsight.DimensionHighlight highlight = new StudentInsight.DimensionHighlight();
                highlight.setDimensionName(dimension);
                highlight.setScore(score);
                highlight.setPercentile(score >= 4.5 ? "前10%" : "前25%");
                highlight.setHighlight(generateDimensionHighlightText(dimension, score));
                highlights.add(highlight);
            }
        }
        
        return highlights;
    }
    
    /**
     * 生成维度亮点文本
     */
    private String generateDimensionHighlightText(String dimension, Double score) {
        return String.format("%s表现优秀（%.1f/5.0），显示出较强的%s", 
            dimension, score, getDimensionDescription(dimension));
    }
    
    /**
     * 获取维度描述
     */
    private String getDimensionDescription(String dimension) {
        Map<String, String> descriptions = new HashMap<>();
        descriptions.put("技术能力", "专业技术掌握程度和实践应用能力");
        descriptions.put("问题解决", "分析问题、解决难题的综合能力");
        descriptions.put("学习能力", "快速学习新知识和适应变化的能力");
        descriptions.put("协作能力", "团队合作和协同工作的能力");
        descriptions.put("沟通能力", "表达交流和人际互动的能力");
        descriptions.put("执行能力", "计划执行和目标达成的能力");
        return descriptions.getOrDefault(dimension, "综合素质");
    }
    
    /**
     * 使用AI生成岗位推荐
     */
    private List<JobRecommendation> generateJobRecommendationsWithAI(
        String studentId,
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis
    ) {
        UserEntity student = dataAggregationService.getStudentById(studentId);
        
        String prompt = buildJobRecommendationPrompt(student, portrait, taskAnalysis);
        
        try {
            String aiResponse = aiClient.chat(prompt);
            return parseJobRecommendations(aiResponse, portrait, taskAnalysis);
        } catch (Exception e) {
            return generateRuleBasedJobRecommendations(portrait, taskAnalysis);
        }
    }
    
    /**
     * 构建岗位推荐的AI提示词
     */
    private String buildJobRecommendationPrompt(
        UserEntity student,
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis
    ) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请根据以下学生的能力画像和任务表现数据，推荐1-3个最适合的岗位：\n\n");
        
        prompt.append("【学生基本信息】\n");
        prompt.append("专业：").append(student.getMajor()).append("\n");
        prompt.append("班级：").append(student.getClassName()).append("\n\n");
        
        prompt.append("【能力雷达图评分】（满分5.0）\n");
        for (int i = 0; i < portrait.getLabels().size() && i < portrait.getScores().size(); i++) {
            prompt.append(portrait.getLabels().get(i)).append("：")
                .append(String.format("%.1f", portrait.getScores().get(i))).append("\n");
        }
        prompt.append("\n");
        
        prompt.append("【任务类别表现】\n");
        prompt.append(taskAnalysis.getAiSummary()).append("\n\n");
        
        prompt.append("请以JSON格式返回，每个岗位包含：\n");
        prompt.append("- jobTitle: 岗位名称\n");
        prompt.append("- jobCategory: 岗位类别\n");
        prompt.append("- matchScore: 匹配度（0-100）\n");
        prompt.append("- recommendationReason: 推荐理由（50字以内）\n");
        prompt.append("- supportingData: 支撑数据点列表（3-5个）\n");
        prompt.append("- requiredSkills: 所需技能列表\n");
        prompt.append("- matchedSkills: 学生已具备的技能\n");
        
        return prompt.toString();
    }
    
    /**
     * 解析AI返回的岗位推荐
     */
    private List<JobRecommendation> parseJobRecommendations(
        String aiResponse,
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis
    ) {
        // 如果AI返回为空，降级到规则生成
        if (aiResponse == null || aiResponse.isEmpty()) {
            return generateRuleBasedJobRecommendations(portrait, taskAnalysis);
        }
        
        try {
            List<JobRecommendation> recommendations = new ArrayList<>();
            
            // 尝试从AI响应中提取JSON部分
            String jsonContent = extractJsonFromResponse(aiResponse);
            if (jsonContent == null) {
                return generateRuleBasedJobRecommendations(portrait, taskAnalysis);
            }
            
            // 使用简单的JSON解析（避免引入Jackson依赖）
            // 支持两种格式：数组 [{...}] 或单个对象 {...}
            List<Map<String, Object>> jobObjects = parseJobListFromJson(jsonContent);
            
            for (Map<String, Object> jobObj : jobObjects) {
                JobRecommendation job = new JobRecommendation();
                
                // 提取必填字段
                job.setJobTitle(getStringValue(jobObj, "jobTitle", "未知岗位"));
                job.setJobCategory(getStringValue(jobObj, "jobCategory", "通用类"));
                job.setMatchScore(getDoubleValue(jobObj, "matchScore", 75.0));
                job.setRecommendationReason(getStringValue(jobObj, "recommendationReason", "综合能力匹配"));
                
                // 提取列表字段
                job.setSupportingData(getStringList(jobObj, "supportingData", new ArrayList<>()));
                job.setRequiredSkills(getStringList(jobObj, "requiredSkills", new ArrayList<>()));
                job.setMatchedSkills(getStringList(jobObj, "matchedSkills", new ArrayList<>()));
                
                recommendations.add(job);
                
                // 最多提取5个推荐
                if (recommendations.size() >= 5) {
                    break;
                }
            }
            
            // 如果解析成功但没有推荐，降级
            if (recommendations.isEmpty()) {
                return generateRuleBasedJobRecommendations(portrait, taskAnalysis);
            }
            
            return recommendations;
            
        } catch (Exception e) {
            return generateRuleBasedJobRecommendations(portrait, taskAnalysis);
        }
    }
    
    /**
     * 从AI响应中提取JSON内容
     */
    private String extractJsonFromResponse(String response) {
        if (response == null) {
            return null;
        }
        
        // 查找JSON数组开始和结束位置
        int arrayStart = response.indexOf("[");
        int arrayEnd = response.lastIndexOf("]");
        
        // 查找JSON对象开始和结束位置
        int objStart = response.indexOf("{");
        int objEnd = response.lastIndexOf("}");
        
        // 优先提取最外层的JSON结构(先出现的)
        boolean arrayFirst = arrayStart >= 0 && (objStart < 0 || arrayStart < objStart);
        
        if (arrayFirst && arrayEnd > arrayStart) {
            return response.substring(arrayStart, arrayEnd + 1);
        }
        
        if (objStart >= 0 && objEnd > objStart) {
            return response.substring(objStart, objEnd + 1);
        }
        
        return null;
    }
    
    /**
     * 简单解析JSON数组（轻量级实现）
     */
    private List<Map<String, Object>> parseJobListFromJson(String json) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        if (json == null || json.trim().isEmpty()) {
            return result;
        }
        
        json = json.trim();
        
        // 如果是数组格式
        if (json.startsWith("[") && json.endsWith("]")) {
            json = json.substring(1, json.length() - 1).trim();
            
            // 简单拆分（处理嵌套的{...}）
            List<String> objects = splitJsonObjects(json);
            for (String obj : objects) {
                Map<String, Object> map = parseJsonObject(obj);
                if (map != null && !map.isEmpty()) {
                    result.add(map);
                }
            }
        } else if (json.startsWith("{") && json.endsWith("}")) {
            // 单个对象
            Map<String, Object> map = parseJsonObject(json);
            if (map != null && !map.isEmpty()) {
                result.add(map);
            } else {
            }
        } else {
        }
        
        return result;
    }
    
    /**
     * 拆分JSON对象数组
     */
    private List<String> splitJsonObjects(String json) {
        List<String> objects = new ArrayList<>();
        int depth = 0;
        int start = 0;
        
        for (int i = 0; i < json.length(); i++) {
            char c = json.charAt(i);
            if (c == '{') {
                if (depth == 0) {
                    start = i;
                }
                depth++;
            } else if (c == '}') {
                depth--;
                if (depth == 0) {
                    objects.add(json.substring(start, i + 1));
                }
            }
        }
        
        return objects;
    }
    
    /**
     * 解析单个JSON对象
     */
    private Map<String, Object> parseJsonObject(String json) {
        Map<String, Object> map = new HashMap<>();
        
        if (json == null || !json.startsWith("{") || !json.endsWith("}")) {
            return map;
        }
        
        json = json.substring(1, json.length() - 1).trim();
        
        // 使用更智能的方式解析JSON - 逐字符扫描
        int i = 0;
        while (i < json.length()) {
            // 跳过空白
            while (i < json.length() && Character.isWhitespace(json.charAt(i))) {
                i++;
            }
            if (i >= json.length()) break;
            
            // 读取key
            if (json.charAt(i) != '"') break;
            i++; // skip opening quote
            int keyStart = i;
            while (i < json.length() && json.charAt(i) != '"') {
                i++;
            }
            String key = json.substring(keyStart, i);
            i++; // skip closing quote
            
            // 跳过冒号
            while (i < json.length() && (Character.isWhitespace(json.charAt(i)) || json.charAt(i) == ':')) {
                i++;
            }
            if (i >= json.length()) break;
            
            // 读取value
            char ch = json.charAt(i);
            if (ch == '"') {
                // 字符串值
                i++;
                int valueStart = i;
                while (i < json.length() && json.charAt(i) != '"') {
                    i++;
                }
                map.put(key, json.substring(valueStart, i));
                i++; // skip closing quote
            } else if (ch == '[') {
                // 数组值
                int arrayStart = i;
                int depth = 0;
                while (i < json.length()) {
                    if (json.charAt(i) == '[') depth++;
                    else if (json.charAt(i) == ']') {
                        depth--;
                        if (depth == 0) {
                            i++;
                            break;
                        }
                    }
                    i++;
                }
                map.put(key, parseJsonArray(json.substring(arrayStart, i)));
            } else if (ch == '{') {
                // 嵌套对象（暂不支持）
                int objStart = i;
                int depth = 0;
                while (i < json.length()) {
                    if (json.charAt(i) == '{') depth++;
                    else if (json.charAt(i) == '}') {
                        depth--;
                        if (depth == 0) {
                            i++;
                            break;
                        }
                    }
                    i++;
                }
                map.put(key, json.substring(objStart, i));
            } else {
                // 数字或布尔值
                int valueStart = i;
                while (i < json.length() && json.charAt(i) != ',' && json.charAt(i) != '}') {
                    i++;
                }
                String value = json.substring(valueStart, i).trim();
                try {
                    map.put(key, Double.parseDouble(value));
                } catch (NumberFormatException e) {
                    map.put(key, value);
                }
            }
            
            // 跳过逗号
            while (i < json.length() && (Character.isWhitespace(json.charAt(i)) || json.charAt(i) == ',')) {
                i++;
            }
        }
        
        return map;
    }
    
    /**
     * 解析JSON数组
     */
    private List<String> parseJsonArray(String json) {
        List<String> list = new ArrayList<>();
        
        if (json == null || !json.startsWith("[") || !json.endsWith("]")) {
            return list;
        }
        
        json = json.substring(1, json.length() - 1).trim();
        
        if (json.isEmpty()) {
            return list;
        }
        
        // 简单拆分（处理引号）
        String[] items = json.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
        
        for (String item : items) {
            item = item.trim();
            if (item.startsWith("\"") && item.endsWith("\"")) {
                list.add(item.substring(1, item.length() - 1));
            } else {
                list.add(item);
            }
        }
        
        return list;
    }
    
    /**
     * 获取字符串值
     */
    private String getStringValue(Map<String, Object> map, String key, String defaultValue) {
        Object value = map.get(key);
        return value != null ? value.toString() : defaultValue;
    }
    
    /**
     * 获取数字值
     */
    private Double getDoubleValue(Map<String, Object> map, String key, Double defaultValue) {
        Object value = map.get(key);
        if (value == null) {
            return defaultValue;
        }
        
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        
        try {
            return Double.parseDouble(value.toString());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
    
    /**
     * 获取字符串列表
     */
    private List<String> getStringList(Map<String, Object> map, String key, List<String> defaultValue) {
        Object value = map.get(key);
        if (value == null) {
            return defaultValue;
        }
        
        if (value instanceof List) {
            List<?> rawList = (List<?>) value;
            List<String> result = new ArrayList<>();
            for (Object item : rawList) {
                result.add(item != null ? item.toString() : "");
            }
            return result;
        }
        
        return defaultValue;
    }
    
    /**
     * 基于规则生成岗位推荐（AI降级方案）
     */
    private List<JobRecommendation> generateRuleBasedJobRecommendations(
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis
    ) {
        List<JobRecommendation> recommendations = new ArrayList<>();
        
        // 空值检查
        if (portrait == null || portrait.getScores() == null || portrait.getScores().isEmpty()) {
            return recommendations;
        }
        
        // 分析最高的能力维度
        int maxIndex = 0;
        double maxScore = 0;
        for (int i = 0; i < portrait.getScores().size(); i++) {
            if (portrait.getScores().get(i) > maxScore) {
                maxScore = portrait.getScores().get(i);
                maxIndex = i;
            }
        }
        
        String topDimension = portrait.getLabels().get(maxIndex);
        
        // 根据优势维度推荐岗位
        JobRecommendation job1 = new JobRecommendation();
        job1.setJobTitle(getJobByDimension(topDimension));
        job1.setJobCategory(getJobCategory(topDimension));
        job1.setMatchScore(maxScore * 20); // 转换为0-100
        job1.setRecommendationReason(String.format("您的%s表现突出（%.1f/5.0），非常适合该岗位", topDimension, maxScore));
        job1.getSupportingData().add(String.format("%s评分%.1f/5.0，位于前列", topDimension, maxScore));
        
        if (taskAnalysis.getPerformanceByType().containsKey("团队任务")) {
            TaskCategoryAnalysis.CategoryPerformance teamPerf = taskAnalysis.getPerformanceByType().get("团队任务");
            job1.getSupportingData().add(String.format("团队任务平均分%.1f，优秀率%.1f%%", 
                teamPerf.getAvgScore() != null ? teamPerf.getAvgScore().doubleValue() : 0,
                teamPerf.getExcellenceRate() != null ? teamPerf.getExcellenceRate() : 0));
        }
        
        recommendations.add(job1);
        
        // 添加更多推荐...
        if (recommendations.size() < 3) {
            JobRecommendation job2 = new JobRecommendation();
            job2.setJobTitle("项目助理");
            job2.setJobCategory("项目管理");
            job2.setMatchScore(75.0);
            job2.setRecommendationReason("综合能力均衡，适合项目协调工作");
            recommendations.add(job2);
        }
        
        return recommendations;
    }
    
    /**
     * 根据维度获取推荐岗位
     */
    private String getJobByDimension(String dimension) {
        Map<String, String> jobMap = new HashMap<>();
        jobMap.put("技术能力", "软件开发工程师");
        jobMap.put("问题解决", "技术支持工程师");
        jobMap.put("学习能力", "研发实习生");
        jobMap.put("协作能力", "团队协调专员");
        jobMap.put("沟通能力", "产品经理");
        jobMap.put("执行能力", "项目管理专员");
        return jobMap.getOrDefault(dimension, "综合管理岗");
    }
    
    /**
     * 获取岗位类别
     */
    private String getJobCategory(String dimension) {
        if (dimension.contains("技术") || dimension.contains("学习")) {
            return "技术研发";
        } else if (dimension.contains("协作") || dimension.contains("沟通")) {
            return "管理协调";
        } else {
            return "综合类";
        }
    }
    
    /**
     * 构建优缺点分析提示词
     */
    private String buildStrengthWeaknessPrompt(
        String studentId,
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis,
        Map<String, Integer> keywords
    ) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请分析以下学生的优点和缺点（各列出3-5条）：\n\n");
        
        prompt.append("【能力评分】\n");
        for (int i = 0; i < portrait.getLabels().size() && i < portrait.getScores().size(); i++) {
            prompt.append(portrait.getLabels().get(i)).append("：")
                .append(String.format("%.1f/5.0", portrait.getScores().get(i))).append("\n");
        }
        
        prompt.append("\n【任务表现】\n");
        prompt.append(taskAnalysis.getAiSummary()).append("\n");
        
        prompt.append("\n【教师评价关键词】\n");
        keywords.entrySet().stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
            .limit(10)
            .forEach(e -> prompt.append(e.getKey()).append("(").append(e.getValue()).append("次) "));
        
        prompt.append("\n\n请分别列出优点和缺点，每条20字以内。");
        
        return prompt.toString();
    }
    
    /**
     * 解析AI返回的优缺点分析
     */
    private void parseStrengthWeaknessResponse(String aiResponse, Map<String, List<String>> result) {
        // 简化实现：按行解析
        String[] lines = aiResponse.split("\n");
        boolean isStrength = true;
        
        for (String line : lines) {
            line = line.trim();
            if (line.contains("缺点") || line.contains("不足") || line.contains("劣势")) {
                isStrength = false;
                continue;
            }
            if (line.isEmpty() || line.length() < 3) {
                continue;
            }
            
            // 移除序号
            line = line.replaceAll("^[0-9]+[.、]\\s*", "");
            
            if (isStrength && result.get("strengths").size() < 5) {
                result.get("strengths").add(line);
            } else if (!isStrength && result.get("weaknesses").size() < 5) {
                result.get("weaknesses").add(line);
            }
        }
    }
    
    /**
     * 基于规则生成优缺点（AI降级方案）
     */
    private void generateRuleBasedStrengthWeakness(
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis,
        Map<String, List<String>> result
    ) {
        // 优点：找出高分维度
        for (int i = 0; i < portrait.getLabels().size() && i < portrait.getScores().size(); i++) {
            if (portrait.getScores().get(i) >= 4.0) {
                result.get("strengths").add(
                    String.format("%s表现优秀，评分%.1f/5.0", 
                        portrait.getLabels().get(i), 
                        portrait.getScores().get(i))
                );
            }
        }
        
        // 缺点：找出低分维度
        for (int i = 0; i < portrait.getLabels().size() && i < portrait.getScores().size(); i++) {
            if (portrait.getScores().get(i) < 3.0) {
                result.get("weaknesses").add(
                    String.format("%s有待提升，当前%.1f/5.0", 
                        portrait.getLabels().get(i), 
                        portrait.getScores().get(i))
                );
            }
        }
        
        // 如果没有明显缺点，添加一般性建议
        if (result.get("weaknesses").isEmpty()) {
            result.get("weaknesses").add("可以进一步提升弱项能力，追求全面发展");
        }
    }
    
    /**
     * 生成综合评价
     */
    private String generateOverallEvaluation(
        String studentId,
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis
    ) {
        double avgScore = portrait.getScores().stream()
            .mapToDouble(Double::doubleValue)
            .average()
            .orElse(0.0);
        
        StringBuilder evaluation = new StringBuilder();
        
        if (avgScore >= 4.0) {
            evaluation.append("该学生综合能力优秀，");
        } else if (avgScore >= 3.5) {
            evaluation.append("该学生综合能力良好，");
        } else {
            evaluation.append("该学生具备基础能力，");
        }
        
        // 找出最强维度
        int maxIdx = 0;
        for (int i = 1; i < portrait.getScores().size(); i++) {
            if (portrait.getScores().get(i) > portrait.getScores().get(maxIdx)) {
                maxIdx = i;
            }
        }
        
        evaluation.append(String.format("在%s方面表现突出。", portrait.getLabels().get(maxIdx)));
        evaluation.append(taskAnalysis.getPerformanceTrend());
        evaluation.append("，具有良好的发展潜力。");
        
        return evaluation.toString();
    }
    
    /**
     * 构建职业建议提示词
     */
    private String buildCareerAdvicePrompt(
        UserEntity student,
        PortraitResponse portrait,
        TaskCategoryAnalysis taskAnalysis
    ) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("请为以下学生提供职业发展建议（100字以内）：\n\n");
        prompt.append("专业：").append(student.getMajor()).append("\n");
        prompt.append("能力平均分：").append(String.format("%.1f/5.0", 
            portrait.getScores().stream().mapToDouble(Double::doubleValue).average().orElse(0.0))).append("\n");
        prompt.append("任务表现：").append(taskAnalysis.getAiSummary()).append("\n");
        
        return prompt.toString();
    }
}
